import {
  drawerConfig,
  drawerFormState,
  drawerTitle,
  drawerVisible,
} from "./drawer";
import {
  defaultModalFormState,
  modalConfig,
  modalFormState,
  modalTitle,
  modalVisible,
} from "./modal";
import { searchConfig } from "./search";
import { tablePage, tableConfig, tableLoading, tableData } from "./table";
import {
  operateType,
  queryParams,
  modalInputValidators,
  drawerInputValidators,
} from "./store";
export const defaultFormState = deepClone(drawerFormState);
export let tmp_proxy: any = null;
export const showDrawer = () => (drawerVisible.value = true);
const showModal = ({ type, record }: { type: string; record?: any }) =>
  (modalVisible.value = true);
export const handleAction = ({ record, type }: any) => {
  operateType.value = type;
  initObjAttr(drawerFormState, defaultFormState);
  initObjAttr(drawerInputValidators, createArray(false, 4));
  initObjAttr(modalInputValidators, createArray(false, 2));
  switch (trimAll(type)) {
    case "add":
      showDrawer();
      drawerTitle.value = $t("base.addBusiness");
      break;
    case "update":
      drawerTitle.value = $t("base.editBusiness");
      showDrawer();
      Object.keys(drawerFormState).forEach((key: any) => {
        drawerFormState[key] = record[key] ?? drawerFormState[key];
      });
      drawerFormState["start_end"] =
        record["start_date"] && record["end_date"]
          ? [$dayjs(record["start_date"]), $dayjs(record["end_date"])]
          : [];
      break;
    case "update->password":
      modalTitle.value = $t("base.changePsd");
      initObjAttr(modalFormState, defaultModalFormState);
      Object.keys(modalFormState).forEach((key: any) => {
        modalFormState[key] = record[key] ?? modalFormState[key];
      });
      showModal({ type, record });
      break;
    case "update->status":
      tmp_proxy.$confirm({
        closable: true,
        icon: null,
        maskClosable: true,
        title: () => <>{$t("base.editBusinessState")}</>,
        style: {
          top: "30%",
        },
        content: (
          <>
            {record.status === 0
              ? `${$t("business0")}"${record.name}"${$t("business1")}`
              : `${$t("business0")}"${record.name}"${$t("business2")}`}
          </>
        ),
        onOk: async () => {
          await businessApi.updateStatus({
            editId: record.id,
          });
          message.success($t("base.updateSucess"));
          fetchList();
        },
      });
      break;
  }
};
export const refreshTable = async (searchParams: any = {}) => {
  tablePage.current = 1;
  initObjAttr(queryParams, searchParams);
  await fetchList();
};
export const fetchList = async () => {
  try {
    tableData.value.length = 0;
    tableLoading.value = true;
    const res: any = await businessApi.query({
      page: tablePage.current,
      page_size: tablePage.pageSize,
      ...queryParams,
    });
    if (res.code != 200) return message.error(res.message);
    tableData.value = res?.data?.list ?? [];
    tablePage.total = res?.data?.attributes?.total ?? 0;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};

export default defineComponent({
  setup(props, { attrs, emit, expose, slots }) {
    const { proxy } = reactive<any>(getCurrentInstance());
    tmp_proxy = proxy;
    const defineSearch = searchConfig();
    const defineDrawer = drawerConfig();
    const defineTable = tableConfig();
    const defineModal = modalConfig();
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    onActivated(() => fetchList());
    return () => (
      <>
        <s-design
          defineTable={defineTable}
          defineSearch={defineSearch}
          defineDrawer={defineDrawer}
          defineModal={defineModal}
        />
      </>
    );
  },
});
